<template>
  <div class="min-h-screen bg-gray-50">
    <div class="pt-20"></div>

    <div class="container mx-auto px-6 py-8">
      <div class="bg-white rounded-xl shadow border border-gray-100 p-6">
        <div class="flex items-start justify-between gap-6">
          <div class="flex items-start gap-3 flex-1">
            <el-button size="small" circle :icon="ArrowLeft" @click="goBack" />
            <div class="flex-1">
              <h1 class="text-2xl font-bold text-gray-900 mb-2">{{ courseTitle }}</h1>
              <p class="text-sm text-gray-600">课程系列 · 共 {{ lessons.length }} 节</p>
            </div>
          </div>
          <div class="flex items-center gap-3">
            <el-button type="primary" size="default" class="rounded-lg" @click="playPreview(lessons[0])">
              立即体验预览
            </el-button>
            <template v-if="classOptions.length">
              <el-select v-model="selectedClassId" class="w-56" placeholder="选择老师班级">
                <el-option v-for="opt in classOptions" :key="opt.id" :label="opt.label" :value="opt.id" />
              </el-select>
              <el-button type="primary" size="default" class="rounded-lg" @click="goToSelectedClass">查看班级</el-button>
            </template>
            <el-button 
              :type="enrolled ? '' : 'success'"
              :disabled="enrolled"
              size="default"
              class="rounded-lg"
              @click="handleEnroll"
            >
              {{ enrolled ? '已报名' : '立即报名' }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="mt-6">
        <div class="bg-white rounded-xl shadow border border-gray-100">
          <div class="p-4 border-b border-gray-100 flex items-center justify-between">
            <h2 class="text-base font-semibold text-gray-900">课程目录</h2>
            <div class="flex items-center gap-2">
              <span class="text-xs text-gray-500">第 1 集免费预览</span>
              <template v-if="classOptions.length">
                <el-select v-model="selectedClassId" size="small" class="w-48" placeholder="选择老师班级">
                  <el-option v-for="opt in classOptions" :key="opt.id" :label="opt.label" :value="opt.id" />
                </el-select>
                <el-button size="small" type="primary" class="rounded px-3" @click="goToSelectedClass">查看</el-button>
              </template>
            </div>
          </div>
          <div class="p-4">
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
              <div
                v-for="(lesson, index) in lessons"
                :key="lesson.id"
                class="rounded-lg border p-3 cursor-pointer hover:border-blue-500 transition-colors"
                :class="index === 0 ? 'border-blue-500 ring-1 ring-blue-500 bg-blue-50/30' : 'border-gray-100'"
                @click="index === 0 ? playPreview(lesson) : goToPay()"
              >
                <div class="flex items-center justify-between mb-2">
                  <span class="text-xs text-gray-500">第 {{ index + 1 }} 集</span>
                  <span v-if="index === 0" class="text-[10px] px-1.5 py-0.5 rounded bg-green-100 text-green-700">免费</span>
                </div>
                <div class="text-sm font-medium text-gray-900 line-clamp-2 leading-5 min-h-[2.5rem]">{{ lesson.title }}</div>
                <div class="mt-2 text-xs text-gray-500">{{ lesson.duration }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { isCourseEnrolled, enrollCourse } from '@/api/course'

const route = useRoute()
const router = useRouter()

const courseId = computed(() => route.params.courseId)

const courseTitle = computed(() => {
  const map = {
    1: '人工智能基础课程 - 系列',
    2: '数据分析实战 - 系列',
    3: '前端开发进阶 - 系列'
  }
  return map[courseId.value] || `课程 ${courseId.value} - 系列`
})

const lessons = ref([
  { id: 'l1', title: '第1节：课程导学（免费体验）', duration: '12:35', preview: true, videoUrl: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4' },
  { id: 'l2', title: '第2节：核心概念与环境配置', duration: '18:20', preview: false },
  { id: 'l3', title: '第3节：基础实战练习', duration: '22:10', preview: false },
  { id: 'l4', title: '第4节：项目结构与工程化', duration: '19:45', preview: false }
])

// 绑定的推荐班级（示例映射，可替换为接口返回）
const boundClassMap = {
  1: [ { id: 11, label: 'AI工程师直播班（2025秋）' }, { id: 13, label: 'AI工程师冲刺班（2025冬）' } ],
  3: [ { id: 9, label: '前端工程化直播班（2025夏）' }, { id: 12, label: '全栈就业班（2025秋）' } ],
  4: [ { id: 12, label: '全栈就业班（2025秋）' } ],
  5: [ { id: 9, label: '前端工程化直播班（2025夏）' } ],
  6: [ { id: 9, label: '前端工程化直播班（2025夏）' } ],
  7: [ { id: 12, label: '全栈就业班（2025秋）' } ],
  8: [ { id: 10, label: '数据分析就业班（2025暑期）' } ]
}
const classOptions = computed(() => boundClassMap[Number(courseId.value)] || [])
const selectedClassId = ref(classOptions.value[0]?.id)

const playPreview = (lesson) => {
  if (!lesson || !lesson.preview) {
    ElMessage.warning('该小节需要购买后观看')
    return
  }
  router.push(`/courses/${courseId.value}/preview/${lesson.id}`)
}

const goToPay = () => {
  ElMessage.info('请前往课程详情购买后学习')
}

const goBack = () => {
  // 返回课程商城并保持“系列课”Tab
  router.push({ path: '/courses', query: { type: 'series' } })
}

const goToBoundClass = (classId) => {
  router.push({ path: `/classes/${classId}/intro`, query: { type: 'class' } })
}
const goToSelectedClass = () => {
  if (selectedClassId.value) {
    goToBoundClass(selectedClassId.value)
  }
}

// 报名状态与操作
const enrolled = ref(false)

onMounted(() => {
  enrolled.value = isCourseEnrolled(courseId.value)
})

const handleEnroll = async () => {
  if (enrolled.value) return
  const res = await enrollCourse(courseId.value)
  if (res?.success) {
    enrolled.value = true
    ElMessage.success(res.message || '报名成功')
  } else {
    ElMessage.error(res?.message || '报名失败')
  }
}
</script>

<style scoped>
</style>



